package vsy.buzzwordbingo.login;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;

import vsy.buzzwordbingo.model.GameCore;

public class PlayerSessionListener implements HttpSessionListener {

	private GameCore gameCore;

	@Override
	public void sessionCreated(HttpSessionEvent se) {
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();

		if (authentication != null) {
			retrieveGameCore(se.getSession()).logoutPlayer(
					authentication.getName());
		}
	}

	// TODO Figure out a better way to access beans from a session listener
	private GameCore retrieveGameCore(HttpSession session) {
		if (gameCore == null) {
			gameCore = (GameCore) WebApplicationContextUtils
					.getWebApplicationContext(session.getServletContext())
					.getBean("gameCore");
		}
		return gameCore;
	}

	public void setGameCore(GameCore gameCore) {
		this.gameCore = gameCore;
	}
}
